#!/bin/bash
# @Author: leiwang
# @Date:   2018-10-08 12:32:56
# @Last Modified by:   leiwang
# @Last Modified time: 2018-11-02 17:04:20
# 1，将monitor启动命令，添加到autorunfile中，支持开机启动
# 2，创建日志文件存放目录./log
date
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin:/bin:${PATH}
# 可执行文件名配置
agent="dbAgent"
monitor="dbMonitor"
# 安装特征码，安装特征码和安装路径的关系是：存在安装路径必然存在安装码，不同安装路径的安装码相同
featurecode='DBaudit_dbagent_V2018101600'
# 动态获取脚本文件所在绝对路径
RUN_PATH=`cd $(dirname $0); pwd -P`

forceFlag=$1

# 安装异常检查项
checkUser(){
  for i in `groups `; do
    if [ $i == "root" ]; then
      return 1
    fi
  done
  return 0
}
checkUser
ret=`echo $?`
if [ $ret != 1 ];then
    echo "WARN: User is not root!"
fi


if [ `uname -s` != "Linux" ]; then
    echo "Error: Operate system is not Linux!"
    exit 2
fi

if [ `getconf LONG_BIT` != "64" ]; then
    echo "WARN: Mathine bits is not 64!"
fi
# 文件缺失
if [ ! -e "${RUN_PATH}/${agent}" ]; then
    echo "Error: File ${agent} is not exist!"
    exit 4
fi

if [ ! -e "${RUN_PATH}/${monitor}" ]; then
    echo "Error: File ${monitor} is not exist"
    exit 5
fi
if [ ! -e "${RUN_PATH}/agent.ini" ]; then
    echo "Error: File agent.ini is not exist"
    exit 6
fi
if [ ! -e "${RUN_PATH}/dbagent_start.sh" ]; then
    echo "Error: File dbagent_start.sh is not exist"
    exit 7
fi
if [ ! -e "${RUN_PATH}/dbagent_stop.sh" ]; then
    echo "Error: File dbagent_stop.sh is not exist"
    exit 8
fi
# CPU限制
if [ "`cat /proc/cpuinfo | grep 'processor' | wc -l | tr -d ' '`"  -lt '4' ]; then
    echo -e "Warnning: The number of processor is less than 4. \nIt is highly advisable to ensure the number of processor greater than or equal to 4, otherwise the dbagent may run some error."
fi
# 内存限制
if [ $[`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`/1024/1024]  -lt 7 ]; then
    echo -e "Warnning: The memory size is less than 8 GB. \nIt is highly advisable to ensure the memory size greater than or equal to 8GB, otherwise the dbagent may run some error."
fi


# 找到支持开机重启的文件，用${autorunfile}表示
# centos /etc/rc.d/rc.local，若/etc/rc.local不是对前者的软链接则不会执行
# ubuntu, debian /etc/init.d/rc.local，若存在/etc/rc.local也会被执行
# suse /etc/rc.d/after.local
# 
if [[ `cat /proc/version | grep coreos | wc -l` -gt 0 ]]; then
    # 假自启文件
    autorunfile="/etc/rc.local"
    if [ ! -e /etc/rc.local ]; then
        touch /etc/rc.local
        echo '#!/bin/bash -e' >> /etc/rc.local
        echo '# This file made by dbagent' >> /etc/rc.local
        chmod +x /etc/rc.local
    fi
elif [ ` lsb_release -a 2>/dev/null | grep -i "Ubuntu" | wc -l` -gt 0 ]; then
    autorunfile="/etc/rc.local"
    if [ ! -e /etc/rc.local ]; then
        touch /etc/rc.local
        echo '#!/bin/bash -e' >> /etc/rc.local
        echo '# This file made by dbagent' >> /etc/rc.local
        chmod +x /etc/rc.local
    fi
elif [ ` lsb_release -a 2>/dev/null | grep -i "Kylin" | wc -l` -gt 0 ]; then
    autorunfile="/etc/rc.local"
    if [ ! -e /etc/rc.local ]; then
        touch /etc/rc.local
        echo '#!/bin/bash -e' >> /etc/rc.local
        echo '# This file made by dbagent' >> /etc/rc.local
        chmod +x /etc/rc.local
    fi
elif [ -e /etc/rc.d/rc.local ]; then
    # centos
    autorunfile="/etc/rc.d/rc.local"
elif [ -e /etc/rc.local ]; then
    # ubuntu, debian
    autorunfile="/etc/rc.local"
elif [ "`uname -a | grep -i debian | wc -l | tr -d ' '`"  -gt "0" ]; then
    # 9.X的Debian
    touch /etc/rc.local
    echo '#!/bin/sh -e' >> /etc/rc.local
    echo '# This file made by dbagent' >> /etc/rc.local
    chmod +x /etc/rc.local
    systemctl start rc-local
    autorunfile="/etc/rc.local"
else
    # suse, 可能有部分ubuntu也存在这个分支里目前
    if [ ! -e /etc/rc.d/after.local ]; then
        touch /etc/rc.d/after.local
        echo '#!/bin/sh -e' >> /etc/rc.d/after.local
        echo '# This file made by dbagent' >> /etc/rc.d/after.local
    fi
    autorunfile="/etc/rc.d/after.local"
fi

if [[ $forceFlag == "force" ]];then
	echo "force install, skip duplicate install check!"
else
	# 避免重复安装，检查原理看开机启动文件/etc/rc.d/rc.local中是否有对应的命令
	if [ -r ${autorunfile} ];then
		if [ "`grep ${featurecode} ${autorunfile} 2>/dev/null | wc -l | tr -d ' '`"  -gt "0" ]; then
			# 存在特征码
			if [ "`grep ${RUN_PATH}/${monitor} ${autorunfile} | wc -l | tr -d ' '`"  -gt "0" ]; then
				# 当前目录有安装
				echo "Error: Install for more then once! You can start the dbagent right now by runing dbagent_start.sh."
				exit
			else
				# 当前目录没有安装
				echo "Error: The dbagent has been installed in other directory, please uninstall it first."
				exit
			fi
		fi
	else
		echo "no read permition for ${autorunfile}"
	fi
fi

# 安装：开机自启，插入到第2行，安装特征码插入第3行
echo "Install dbagent..."
if [[ `cat /proc/version | grep coreos | wc -l` -gt 0 ]]; then
    # 实际开机启动命令
    echo -e "[Unit]\nDescription=dbagent\n\n[Service]\nType=forking\nRestart=no\nExecStart=${RUN_PATH}/${monitor}\n\n[Install]\nWantedBy=multi-user.target\n" > /etc/systemd/system/dbagent.service
    systemctl daemon-reload
    systemctl enable dbagent
fi

#判断写权限
if [ -w ${autorunfile} ];then
	temNAME="${RUN_PATH}/${monitor} 1>/dev/null 2>&1 &"
	sed -i "2i ${temNAME}" ${autorunfile}
	if [[ $forceFlag == "force" ]];then
		#升级回退需保留特征码
		echo "upgrade restore mode skip add feature code".
	else
		sed -i "3i # ${featurecode}" ${autorunfile}
	fi
	if [[ `tail -n 1 ${autorunfile}` != "exit 0" ]] ; then
		echo "exit 0" >> ${autorunfile}
	fi
else
	echo "cannot write ${autorunfile}"
fi

chmod a+x ${autorunfile}

# 创建日志文件目录
mkdir ${RUN_PATH}/log 1>/dev/null 2>/dev/null
#create file dir to support local audit
mkdir ${RUN_PATH}/temp 1>/dev/null 2>/dev/null
mkdir ${RUN_PATH}/audit 1>/dev/null 2>/dev/null

# 检查安装结果
if [ "`grep ${RUN_PATH}/${monitor} ${autorunfile} | wc -l | tr -d ' '`"  != "1" ]; then
    echo "Install dbagent failed, but start agent now"
else
    echo "Install dbagent success"
fi

#权限
chmod +x ${RUN_PATH}/dbagent_start.sh
chmod +x ${RUN_PATH}/dbagent_stop.sh 
chmod +x ${RUN_PATH}/${agent}
chmod +x ${RUN_PATH}/${monitor}
chmod +x ${RUN_PATH}/tool/getip

#bash installHook.sh
# 执行启动脚本
if [[ $forceFlag == "force" ]];then
	bash -vx ${RUN_PATH}/dbagent_start.sh
else
	${RUN_PATH}/dbagent_start.sh
fi